<?php


namespace App\Http\Controllers\Api;

use App\Businesses\BusinessState;
use App\Constant\ApiV2Constant;
use App\Http\Requests\Company\AppraiseRequest;
use App\Services\Business\Models\Anthology;
use App\Services\Business\Models\Appraise;
use App\Services\Business\Services\CategoryService;
use App\Services\Business\Interfaces\CategoryServiceInterface;
use App\Services\Business\Models\Article;
use App\Services\Business\Models\Category;
use App\Services\Member\Models\User;
use App\Services\Member\Services\UserService;
use App\Zesow\Cache\Inc\Inc;
use App\Zesow\Cache\Inc\ArticleViewIncItem;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Business\Services\AnthologyService;
use App\Services\Business\Interfaces\AnthologyServiceInterface;
use App\Services\Business\Services\ArticleService;
use App\Services\Business\Interfaces\ArticleServiceInterface;
use App\Services\Business\Interfaces\PromotionServiceInterface;
use App\Services\Business\Services\PromotionService;
use App\Services\Business\Interfaces\RecommendServiceInterface;
use App\Services\Business\Services\RecommendService;


class
ArticleController extends BaseController
{
    /**
     * @var AnthologyService
     */
    protected $anthologyService;

    /**
     * @var UserService
     */
    protected $userService;
    /**
     * @var ArticleService
     */
    protected $articleService;
    /**
     * @var PromotionService
     */
    protected $promotionService;
    /**
     * @var RecommendService
     */
    protected $recommendService;
    /**
     * @var BusinessState
     */
    protected $businessState;

    /**
     * @var CategoryService
     */
    protected $categoryService;


    public function __construct(
        AnthologyServiceInterface $anthologyService,
        BusinessState             $businessState,
        ArticleServiceInterface   $articleService,
        UserServiceInterface      $userService,
        RecommendServiceInterface $recommendService,
        CategoryServiceInterface  $categoryService,
        PromotionServiceInterface $promotionService
    )
    {
        $this->anthologyService = $anthologyService;
        $this->businessState = $businessState;
        $this->articleService = $articleService;
        $this->recommendService = $recommendService;
        $this->userService = $userService;
        $this->categoryService = $categoryService;
        $this->promotionService = $promotionService;


    }


    public function index(Request $request)
    {

        $categoryId = $request->input('cid', 0);
        $keywords = $request->input('keywords', 0);
        $size = $request->input('size', 20);
        $companyId = $request->input('company_id');
        $articles = Article::query()
            ->select(['id', 'title', 'thumb', 'favorite_count', 'thumbsup_count', 'short_description', 'category_id', 'my_category_id', 'is_show', 'user_id', 'updated_at', 'created_at'])
            ->when($companyId, function ($query) use ($companyId) {
                return $query->where('company_id', $companyId);
            })
            ->when($keywords, function ($query) use ($keywords) {
                return $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->when($categoryId, function ($query) use ($categoryId) {
                $ids = [$categoryId];
                $childrenIds = Category::query()
                    ->where('parent_id', $categoryId)
                    ->select(['id'])
                    ->get()
                    ->pluck('id')
                    ->toArray();
                $ids = array_merge($ids, $childrenIds);
                $query->whereIn('category_id', $ids);
            })
            ->with(['category:id,name', 'user'])
            ->where('is_show', 1)
            ->orderByDesc('created_at')
            ->paginate($size);
        $users = User::query()
            ->select(['id', 'nick_name', 'avatar', 'mobile'])
            ->whereIn('id', array_column($articles->items(), 'user_id'))
            ->get()
            ->keyBy('id');

        return $this->successData(compact('articles', 'users'));
    }




    public function detail(Request $request, $id)
    {


        $keywords = $request->input('keywords', '');
        //这里用来临时加权限
        $article = $this->articleService->get($id);
        // 视频浏览次数自增
        Inc::record(new ArticleViewIncItem($id));

        $relativeArticles = [];

        //通过关键字搜索到的文章默认带上关键字;把相关的文章检索出来夺
        if (count($article['tags']) > 0 || !empty($keywords)) {
            $relativeArticles = $this->articleService->findRelativeArticles($keywords, $article);
        }

        //推荐的内容
        $recommends = ($this->articleService->hasRecommends($id)) ? $this->recommendService->getRecommends('article', $id) : [];


        $isBuy = $article['anthology']['is_free'] == 1 ?? 0;
        $isFavorited = false;
        $isFollowed = false;
        $isThumbsuped = false;

        if ($this->check()) {
            $isBuy = $this->businessState->canReadArticle($this->user(), $article);
            $isFollowed = $this->userService->isFollowed($this->id(), $article['user_id']);
            $isFavorited = $this->userService->isFavorited($this->id(), $id, Article::class);
            $isThumbsuped = $this->userService->isThumbsuped($this->id(), $id, Article::class);

        }
        return $this->successData(compact("article", 'isFollowed', 'isFavorited', "isBuy", 'isThumbsuped', 'relativeArticles', 'recommends'));

    }


    public function read($anthologyId, $articleId)
    {
        $article = Article::query()->find($articleId);
        $anthology = Anthology::query()->find($article['anthology_id']);
        $chapters = $this->anthologyService->chapters($article['anthology_id']);
        $chapters = arr2_clear($chapters, ApiV2Constant::MODEL_COURSE_CHAPTER_FIELD);
        $isBuy = false;
        $canSen = true;

        $articles = $this->anthologyService->articles($article['anthology_id']);
        ['prev_id' => $prev_id, 'next_id' => $next_id] = $this->anthologyService->prevAndNext($articleId, $anthology->id);
        return $this->successData(compact('articles', 'chapters', 'article', 'prev_id', 'next_id', 'anthology', 'canSen', 'isBuy'));

    }


}
